<template>
    <el-form ref="formRef" :model="form" label-width="80px">
        <el-form-item label="分类名称" prop="name" style="width: 92%">
            <el-input
                v-model="form.name"
                placeholder="请输入分类名称"
            ></el-input>
        </el-form-item>
        <!-- 二级分类 -->
        <el-form-item label="分类级别">
            <el-radio-group v-model="showMore">
                <el-radio :label="false" :disabled="form.id !== 0 && !form.pid">
                    一级分类
                </el-radio>
                <el-radio :label="true" :disabled="form.id !== 0 && !form.pid">
                    二级分类
                </el-radio>
            </el-radio-group>
        </el-form-item>
        <!-- 分类选择 -->
        <el-form-item label="分类选择" prop="pid" v-show="showMore">
            <el-select v-model="form.pid" placeholder="请选择分类">
                <el-option
                    v-for="item in categroylist"
                    :key="item.id"
                    :label="item.cname"
                    :value="item.id"
                ></el-option>
            </el-select>
        </el-form-item>
        <!-- 分类图片 -->
        <el-form-item label="分类图片" v-show="showMore">
            <el-upload
                v-model:file-list="fileList"
                class="upload-demo"
                ref="uploadRef"
                :action="uploadPictureURL()"
                :headers="{ jwt: token }"
                :data="{ type: 'category_picture' }"
                :limit="1"
                :on-success="uploadSuccess"
            >
                <el-button type="primary">请选择图片</el-button>
                <template #tip>
                    <div class="el-upload__tip">图片文件大小不超过500KB</div>
                </template>
            </el-upload>
        </el-form-item>
        <!-- 按钮 -->
        <el-form-item>
            <el-button type="primary" v-if="id" @click="editSubmint">
                修改
            </el-button>
            <el-button type="primary" v-else @click="addSubmint">
                添加
            </el-button>
            <el-button type="info" @click="btnCancel">重置</el-button>
        </el-form-item>
    </el-form>
</template>

<script setup>
import {
    getCategoryList,
    addCategory,
    getCategory,
    editCategory,
    uploadPictureURL,
} from "../api/api";
import { onMounted, ref, reactive } from "vue";
import notification from "../utils/notification";
import useToken from "../store/token";

const { token } = useToken();
const categroylist = ref([]);
const showMore = ref(false);
const formRef = ref();
const uploadRef = ref();
const props = defineProps({ id: { type: Number } });

const emit = defineEmits("success");
const form = reactive({
    id: props.id,
    name: "",
    pid: "",
    picture: "",
});
const fileList = ref([]);
onMounted(() => {
    loadCategroy();
});

//查询所有分类
const loadCategroy = async () => {
    //id存在就是修改
    if (form.id) {
        //props.id会赋值给form对象
        //根据 id查出当前的分类信息
        const data = await getCategory({ id: form.id });
        //处理图片字符串
        if (data.picture !== "") {
            const fileName = data.picture.substring(
                data.picture.lastIndexOf("/") + 1
            );
            if (fileName) {
                fileList.value = [{ name: fileName, url: data.picture }];
            }
        }
        //查询出的结果，拷贝到form中
        Object.assign(form, data);
    }
    const list = await getCategoryList();
    categroylist.value = list.filter((item) => item.pid == 0);
    showMore.value = form.pid != 0;
};

//重置表单
const btnCancel = () => {
    formRef.value.resetFields();
    form.picture = "";
    uploadRef.value.clearFiles();
    loadCategroy();
};
//清空所有内容
const resetForm = (id) => {
    form.id = id;
    btnCancel();
};

defineExpose({ resetForm });

//添加功能
const addSubmint = async () => {
    const data = {
        name: form.name,
        picture: form.picture,
        pid: form.pid,
    };
    if (await addCategory(data)) {
        emit("success");
    }
};
//修改功能
const editSubmint = async () => {
    if (await editCategory(form)) {
        emit("success");
    }
};

//图片上传成功
const uploadSuccess = (response) => {
    const { errno, errmsg, data } = response;
    if (errno !== 0) {
        notification({
            message: errmsg,
            type: "error",
        });
    } else {
        if (errmsg !== "") {
            notification({
                message: errmsg,
                type: success,
            });
        }
        form.picture = data.savepath;
    }
};
</script>